/**
 * 功能：钱包余额
 * 入口：
 * 
 */
import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import {PullLoad,Header,LoadMore} from 'components/index'
import {hashHistory, Link } from 'react-router';
import {DanluJsBridge,logger,http} from 'common/index'
import './wallet.less'
import {Remainder,BankCard,Caption,BillList,BillSummary,BillDetail} from './subpage/index'

import axios from 'axios'
// redux
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as walletInfoActionsFromOtherFile from '../../store/actions/walletinfo' 

class Bmikece extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            billList : [],
            billPageIndex : 0,
            billPageSize : 20,
            billHasMore : true,
            screenHeight : 0
        }
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    }
    //组件将要加载完成
    componentWillMount(){
        var _this = this;
        var clientHeight = document.documentElement.clientHeight
        var screenHeight = clientHeight - 64 - 44
        this.setState({
            screenHeight : screenHeight
        })

        DanluJsBridge.callHandler('setTitle', {
            title: '钱包余额',
            color: '#ffffffff',
        })
        
        
        this.getBalance();
        this.tradeQuery(this.props.location.state.acc_type);
    }
    componentWillUnmount (){

        this.props.walletinfoActions.walletInfoUpdate({
            Ceiling : false
        })
    }
    // 提现
    goTransfer(){
        hashHistory.push({
            pathname : '/transfer',
            state:{
                acc_type:209
            }
        })
    }
    // 转入公司账户
    goDeposit(){
        hashHistory.push({
            pathname : '/deposit',
            state:{
                acc_type:this.props.location.state.acc_type
            }
        })
    }

    //查询余额
    getBalance (){
        var _this = this;
        return new Promise(function(resolve,reject){
             var reqData = {
                "userId": _this.props.walletinfo.user.userId,
                "companyId": _this.props.walletinfo.user.companyId
            }
            http.post('/dlpcweb/dlpc/pc/V1/wallet/getBalance',reqData).then((data) =>{
                var balanceDetail = data.balanceDetail || []
                _this.props.walletinfoActions.walletInfoUpdate({
                    balanceDetail : balanceDetail,
                    withDrawFee : data.withDrawFee
                })
                resolve();
            }).catch(function(e){
                resolve();
            })           
        })
    }
    //查询账户账单流水
    tradeQuery (accType){

        var _this = this;
        //获取当前日期
        var time  = new Date();
        var year = time.getFullYear().toString()
        var month = time.getMonth()+1 < 10 ? "0"+(time.getMonth()+1).toString() : (time.getMonth()+1).toString()
        var day = time.getDate()+1 < 10 ? "0"+(time.getDate()+1).toString() : (time.getDate()+1).toString()
        var today = year + month + day
        var pageIndex = _this.state.billPageIndex +1 
        var pageSize = _this.state.billPageSize 
        var reqData = {
            "userId":_this.props.walletinfo.user.userId, 
            "companyId":_this.props.walletinfo.user.companyId, 
            "accType": accType,
            "startDate":"20180301",
            "endDate": today,
            "pageIndex":pageIndex.toString(),
            "pageSize":pageSize.toString()

        }
        return new Promise(function(resolve,reject){
            http.post('/dlpcweb/dlpc/pc/V1/wallet/tradeQuery',reqData,{custom:true}).then( (data) => {
                if (data.status == 0){
                    var billList = _this.state.billList
                    billList = billList.concat(data.data_list)
                    var billPageIndex = _this.state.billPageIndex
                       
                    //判断是否含有更多
                    if (data.index * data.size <= data.total) {
                        _this.setState({
                            billList : billList,
                            billPageIndex : ++billPageIndex,
                            billHasMore : true
                        }) 
                        resolve(true)
                    }else{
                        var hasMore = false
                        _this.setState({
                            billList : billList,
                            billHasMore : hasMore
                        }) 
                        reject(false)
                    }  
                }else{
                    DanluJsBridge.callHandler('alert', {
                        title: '提示',
                        message: "获取账单失败",
                        button: '我知道了'
                    })
                    reject(false)
                }
            })
        })
    }

    //下拉刷新
    handRefreshing(callback){
        var queryArr = []
        this.setState({
            billPageIndex : 0,
            billList : [],
            billHasMore : true
        },function(){
            var acc_type = this.props.location.state.acc_type
            queryArr.push(this.getBalance())
            queryArr.push(this.tradeQuery(acc_type))
            Promise.all(queryArr).then(() =>{
                callback();
            },() =>{
                callback();
            }).catch(() =>{
                callback();
            })
            
        })
    }
    // 上拉加载
    handLoadMore (callback){
        if (!this.state.billHasMore) {
            setTimeout(function(){
                callback(true)
            },500)
            
        }else{
            this.tradeQuery(this.props.location.state.acc_type).then(function(){
                console.log('hasMore:true')
                callback(true)
            },function(){
                console.log('hasMore:false')
                callback(false)
            }).catch(() =>{
                console.log('hasMore:false')
                callback(false)
            })
        }
        

    }



    render() {

        var balance = {}
        var companyBalance = null
        var balanceDetail= this.props.walletinfo.balanceDetail || []
        balanceDetail.forEach((item) =>{
            if (item.acc_type ==  this.props.location.state.acc_type){
                return balance = item
            }else if(item.acc_type == '208'){
                companyBalance = item
            }
        })
        this.state.balance = balance
        return (
        	<div className="Bmikece">
        		<Header title="钱包余额" className="wallet-hader">
                    <span>明细222</span>
                </Header>
                {/*<PullLoad headerClass="wallet-hader" screenHeight={this.state.screenHeight} handRefreshing={this.handRefreshing.bind(this)} handLoadMore={this.handLoadMore.bind(this)} hasMore={this.state.billHasMore}>*/}
                    <div className=" " id="Bmikece">
                        <div className="wallet-hader">
                            <Remainder balance={balance} />
                        </div>
                        <div className={this.props.walletinfo.Ceiling ? 'Ceiling' : 'Ceiled'}>
                            <Caption title="我的账单" >
                                <span onClick={this.gotoTop.bind(this)} className="home-btn">回到顶部</span>
                            </Caption>
                        </div>
                        <div id="BillList">
                            <BillList billList={this.state.billList} accountStatus="0" accType={this.props.location.state.acc_type}/>
                        </div>
                        {
                            this.state.billList &&this.state.billList.length ? <LoadMore  hasMore={this.state.billHasMore} loadMoreFn={this.handLoadMore.bind(this)}/> : ''
                        }
                        
                        <div style={{marginBottom:54}}></div>
                    </div>
                {/*</PullLoad>*/}
                <div>
                    
                    <div className="bmike-btn-group">
                        {
                            balance.acc_type == '209' && companyBalance ? <div className="fill-item" >
                                <button className="bmike-btn" disabled={parseFloat(balance.balance)==0} onClick={this.goTransfer.bind(this)}>转入公司账户</button>
                            </div> : ''
                        }
                        
                        <div className="fill-item" >
                            <button className="bmike-btn" disabled={parseFloat(balance.balance)==0} onClick={this.goDeposit.bind(this)}>提 现</button>
                        </div>
                    </div>
                </div>
        	</div>
        )
    }

    //回到顶部
    gotoTop (){
        window.scrollTo(0,0)
    }
    
}


// -------------------redux react 绑定--------------------

function mapStateToProps(state) {
    return {
        walletinfo: state.walletinfo
    }
}

function mapDispatchToProps(dispatch) {
    return {
        walletinfoActions: bindActionCreators(walletInfoActionsFromOtherFile, dispatch)
    }
}
export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Bmikece)